//
//  NewsListGetDataModel.m
//  ZhiHuDaily
//
//  Created by albert on 16/8/30.
//  Copyright © 2016年 albert. All rights reserved.
//

#import "NewsListGetDataModel.h"
#import "NetworkingTool.h"
#import "SQLiteManager.h"
#import "NewsDetailModel.h"
#import "NewsDetailExtraModel.h"
#import <MJExtension/MJExtension.h>
#import "JKDateTool.h"
#import "NewsListModel.h"
#import "Reachability.h"
#import "JKProgressHUD.h"

static Reachability *_reach;

@implementation NewsListGetDataModel
/** 加载首页最新数据 */
+ (void)loadLatestDatafWithFinishedBlock:(void(^)(NSDictionary *dict, NSError *error))finished{
    
    // 从本地获取最新数据
    NSString *dateStr = nil;
    NSArray *lists = nil;
    NSArray *topLists = nil;
    NSArray *stories = nil;
    NSDictionary *dict = [SQLiteManager queryLatestStoryList];
    if (dict != nil) {
        dateStr = dict[JKStoryDateKey];
        lists = dict[JKStoryListKey];
        topLists = dict[JKTopStoryListKey];
        stories = [NewsListModel mj_objectArrayWithKeyValuesArray:lists];
        
        // 仅在网络不可用时才真正加载本地数据，因为首页数据会一直变化
        _reach = [Reachability reachabilityWithHostName:@"baidu.com"];
        if (_reach.currentReachabilityStatus == NotReachable) {
            !finished ? : finished(@{JKStoryDateKey : dateStr, JKStoryListKey : stories, JKTopStoryListKey : topLists}, nil);
            [JKProgressHUD showErrorWithStatus:@"您的网络貌似有点问题~~"];
            return;
        }
    }
    
    // 从网络加载最新数据
    NSString *urlStr = @"news/latest";
    [[NetworkingTool sharedNetworkingTool] loadDataWithUrl:urlStr parameters:nil finishedBlock:^(id  _Nullable responseObj, NSError * _Nullable error) {
        if (error || responseObj == nil) {
            if (dict == nil) {
                !finished ? : finished(nil, error);
                return;
            }
            !finished ? : finished(@{JKStoryDateKey : dateStr, JKStoryListKey : stories, JKTopStoryListKey : topLists}, nil);
            return;
        }
        NSArray *lists = responseObj[@"stories"];
        NSArray *topLists = responseObj[@"top_stories"];
        NSString *dateStr = responseObj[@"date"];
        NSArray *stories = [NewsListModel mj_objectArrayWithKeyValuesArray:lists];
        
        !finished ? : finished(@{JKStoryDateKey : dateStr, JKStoryListKey : stories, JKTopStoryListKey : topLists}, nil);
        
        [SQLiteManager cacheStoryLists:lists date:dateStr isTop:NO isLatest:YES isMore:NO];
        [SQLiteManager cacheTopStories:topLists date:dateStr];
    }];
}

/** 加载新闻详情数据 */
+ (void)loadDetailDataWithID:(int)ID detailBlock:(void(^)(NewsDetailModel *detailModel, NSError *error))detailBlock extraBlock:(void(^)(NewsDetailExtraModel *extraModel, NSError *error))extraBlock{
    
    // 获取详情扩展数据 评论条数  （扩展数据变化较快，所以不缓存了）
    NSString *urlStr = [NSString stringWithFormat:@"story-extra/%d", ID];
    [[NetworkingTool sharedNetworkingTool] loadDataWithUrl:urlStr parameters:nil finishedBlock:^(id  _Nullable responseObj, NSError * _Nullable error) {
        if (error) return;
        
        NewsDetailExtraModel *extraModel = [NewsDetailExtraModel mj_objectWithKeyValues:responseObj];
        !extraBlock ? : extraBlock(extraModel, nil);
    }];
    
    // 从本地获取详情数据
    NSDictionary *detailDict = [SQLiteManager queryStoryDetailWithID:ID];
    if (detailDict != nil) {
        NewsDetailModel *model = [NewsDetailModel mj_objectWithKeyValues:detailDict];
        !detailBlock ? : detailBlock(model, nil);
        return;
    };
    
    // 没有从本地获取到详情数据，从网络加载
    NSString *detailUrlStr = [@"news/" stringByAppendingString:@(ID).stringValue];
    [[NetworkingTool sharedNetworkingTool] loadDataWithUrl:detailUrlStr parameters:nil finishedBlock:^(id  _Nullable responseObj, NSError * _Nullable error) {
        if (error) return;
        
        NewsDetailModel *model = [NewsDetailModel mj_objectWithKeyValues:responseObj];
        !detailBlock ? : detailBlock(model, nil);
        
        // 执行缓存
        [SQLiteManager cacheDetail:responseObj ID:ID justCache:NO];
    }];
}

/** 加载首页更多数据 */
+ (void)loadMoreDataWithDate:(int)date finishedBlock:(void(^)(NSDictionary *dict, NSError *error))finished{
    
    int beforeDate = [JKDateTool getPreviousDayOfSpecifiedDate:date];
    NSDictionary *listsDict = [SQLiteManager queryStoryListWithDate:beforeDate];
    if (listsDict != nil) {
        NSArray *lists = listsDict[JKStoryListKey];
        NSString *dateStr = listsDict[JKStoryDateKey];
        NSMutableArray *modelArr = [NewsListModel mj_objectArrayWithKeyValuesArray:lists];
        if (lists.count > 1) {
            !finished ? : finished(@{JKStoryDateKey : dateStr, JKStoryListKey : modelArr}, nil);
            return;
        }
    }
    
    // 数据库没有取得数据，从网络请求数据
    NSString *urlStr = [@"news/before/" stringByAppendingString:@(date).stringValue];
    [[NetworkingTool sharedNetworkingTool] loadDataWithUrl:urlStr parameters:nil finishedBlock:^(id  _Nullable responseObj, NSError * _Nullable error) {
        if (error) return;
        NSArray *stories = responseObj[@"stories"];
        NSString *dateStr = responseObj[@"date"];
        
        NSMutableArray *modelArr = [NewsListModel mj_objectArrayWithKeyValuesArray:stories];
        !finished ? : finished(@{JKStoryDateKey : dateStr, JKStoryListKey : modelArr}, nil);
        
        // 执行缓存
        [SQLiteManager cacheStoryLists:stories date:dateStr isTop:NO isLatest:NO isMore:YES];
    }];
}
@end
